package com.cyh.myapplication;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.cyh.aidlservice.Book;
import com.cyh.aidlservice.IBookManager;
import com.cyh.aidlservice.IOnNewBookArrivedListener;

import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private static final int MESSAGE_NEW_BOOK_ARRIVED = 1;
    private IBookManager mRemoteBookManager;
    IBinder iBinder;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVED:{
                    Log.i(TAG, "receive new book:" + msg.obj);
                }break;
                default:
                    super.handleMessage(msg);
            }
        }
    };
    private IOnNewBookArrivedListener mOnNewBookArrivedListener=new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book newBook) throws RemoteException {
            //当前是子线程
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVED, newBook).sendToTarget();
        }
    };

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iBinder = service;
            IBookManager bookManager = IBookManager.Stub.asInterface(service);
            try{
                mRemoteBookManager = bookManager;
                //iBinder.linkToDeath(mDeathRecipient, 0);  //监听服务倍杀死重连
                List<Book> list = bookManager.getBookList();
                Log.i(TAG, "ServiceConnection-type: " + list.getClass().getCanonicalName());
                Log.i(TAG, "ServiceConnection-list: " + list);
                Book newBook = new Book(3, "C++");
                bookManager.addBook(newBook);
                List<Book> newList = bookManager.getBookList();
                Log.i(TAG, "ServiceConnection-list-2: " + newList);
                mRemoteBookManager.registerListener(mOnNewBookArrivedListener);
            }catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //可以在这里做重连 或者监听bind的DeathRecipient 做重连
            mRemoteBookManager = null;
            Log.e(TAG, "binder died");

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent=new Intent();
        intent.setComponent(new ComponentName("com.cyh.aidlservice","com.cyh.aidlservice.BookManagerService"));
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        findViewById(R.id.btn_notifyService).setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        if(mRemoteBookManager != null && mRemoteBookManager.asBinder().isBinderAlive()) {
            try{
                Log.i(TAG, "unregister listener:" + mOnNewBookArrivedListener);
                mRemoteBookManager.unregisterListener(mOnNewBookArrivedListener);
            }catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        unbindService(mConnection);
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_notifyService:{
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //如果服务端很耗时，会anr，所以要在线程中， 不耗时可以在UI线程
                            mRemoteBookManager.notifyBook();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }break;
        }
    }

    /**
     * 监听Binder是否死亡
     */
    private IBinder.DeathRecipient mDeathRecipient = new IBinder.DeathRecipient() {
        @Override
        public void binderDied() {
            if (mRemoteBookManager == null) {
                return;
            }
            mRemoteBookManager.asBinder().unlinkToDeath(mDeathRecipient, 0);
            mRemoteBookManager = null;
            //重新绑定
            //bind();
        }
    };

}
